import styles from './popup.module.css'

interface Ipopup {
    width?: string;
    height?: string;
    title?: string;
    pos?: string;
    mask?: boolean;
    content?: (content:HTMLElement) => void;
}

interface Icomponent {
    tempContainer: HTMLElement;
    init: () => void;
    template: () => void;
    handle: () => void;
}

function popup(options: Ipopup) {
    return new Popup(options)
}

class Popup implements Icomponent {
    tempContainer = document.createElement('div');
    mask = document.createElement('div');

    constructor(private settings: Ipopup) {
        this.settings = Object.assign({
            width: '520',
            height: '520',
            title: '提示',
            pos: 'center',
            mask: true,
            content: function () {
            }
        }, this.settings)
        this.init()
    }

    // 初始化
    init() {
        this.settings.mask && this.createMask();
        this.template();
        this.handle();
        this.createCallback();
    }

    // 创建模板
    template() {
        this.tempContainer.className = styles.contentWrap;
        this.tempContainer.innerHTML =
            `
        <div class="${styles.title}">${this.settings.title}</div>
        <div class="${styles.content}"></div>
        `;
        document.body.appendChild(this.tempContainer);
        this.tempContainer.style.width = this.settings.width + 'px';
        this.tempContainer.style.height = this.settings.height + 'px';
        if (this.settings.pos === 'left') {
            this.tempContainer.style.left = '0px';
            this.tempContainer.style.bottom = '0px';
        } else if (this.settings.pos === 'right') {
            this.tempContainer.style.right = '0px';
            this.tempContainer.style.bottom = '0px';
        } else {
            this.tempContainer.style.left = (window.innerWidth - this.tempContainer.offsetWidth) / 2 + 'px';
            this.tempContainer.style.top = (window.innerHeight - this.tempContainer.offsetHeight) / 2 + 'px';
        }
    }

    // 事件操作
    handle() {
        this.mask.addEventListener('click', () => {
            document.body.removeChild(this.tempContainer);
            this.settings.mask && document.body.removeChild(this.mask)
        })
    }

    createCallback(){
        const popupContent = this.tempContainer.querySelector(`.${styles.content}`);
        this.settings.content&&this.settings.content(popupContent)

    }

    createMask() {
        this.mask = document.createElement('div');
        this.mask.className = styles.mask;
        document.body.appendChild(this.mask);
    }

}

export default popup;
